var api = require("../../api.js"),
  app = getApp();
import {
  $Login
} from '../../components/base.js'
var rpn = require('../../utils/rpn.js')
var bmap = require('../../asset/plugins/bmap-wx.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    act_data: {},
    isHavedCollect: '',
    showModalStatus: false,
    name: '',
    business: '',
    job: '',
    message: '',
    invite_open_id: '',
    enrollsData: [],
    enroll_num: 0,
    customFields: [],
    comm_id: '',
     /** 是否支付失败 0 否 1 是  */
    pay_fail: '0',
    /** 顶部进度条值 */
    value: 0 
  },
  onLoad: function(options) {
    /** 是否已授权 */
    getApp().is_empower();
    console.log(options)
    this.setData({
      id: options.id,
      invite_open_id: options.invite_open_id || ''
    })
  },
  onShow: function() {
    wx.showLoading({
      title: "数据加载中"
    });
    setTimeout(() => {
      var that = this;
      $Login();
      this.getEnrolls();
      if (this.data.invite_open_id && this.data.invite_open_id != undefined) {
        let shareData = {
          act_id: this.data.id,
          open_id: app.globalData.wxUserInfo.openId || '',
          invite_open_id: this.data.invite_open_id
        }
        console.log(shareData)
        wx.request({
          url: api.active.shareAct,
          data: shareData,
          method: "POST",
          header: {
            "content-type": "application/x-www-form-urlencoded"
          },
          success(res) {
            setTimeout(() => {
              wx.hideLoading()
              const content = res.data.data.actDesc;
              res.data.data.actDesc = that.formatRichText(content);
              that.setData({
                act_data: res.data.data,
                isHavedCollect: res.data.data.isHavedCollect,
                customFields: res.data.data.f_json,
                comm_id: res.data.data.comm_id
              })
            }, 300)
          }
        });
      } else {
        let sendData = {
          act_id: this.data.id,
          open_id: app.globalData.wxUserInfo.openId
        }
        wx.request({
          url: api.details.actDetail,
          data: sendData,
          header: {
            "content-type": "application/json"
          },
          method: 'GET',
          success(res) {
            setTimeout(() => {
              wx.hideLoading()
              const content = res.data.data.actDesc;
              res.data.data.actDesc = that.formatRichText(content);
              that.setData({
                act_data: res.data.data,
                isHavedCollect: res.data.data.isHavedCollect,
                customFields: res.data.data.f_json,
                comm_id: res.data.data.comm_id
              })
            }, 300)
            if (that.data.pay_fail == '1') {
              /** 延迟1s 提示 */
              setTimeout(() => {
                wx.showToast({
                  title: '支付失败',
                  image: '../../images/pay_fail_01.png',
                  duration: 2000
                })
              }, 1000);
            }
          }
        })
      }
    }, 1000);
  },
  onShareAppMessage: function() {
    return {
      title: this.data.act_data.title,
      path: `pages/activedetial/activedetial?id=${this.data.id}&invite_open_id=${app.globalData.wxUserInfo.openId || ''}`,
      success: function(res) {},
      fail: function(res) {}
    }
  },

  /** 地图导航 */
  map: function() {
    /** 经纬度 */
    if (this.data.act_data.lng && this.data.act_data.lat) {
      wx.openLocation({
        latitude: Number(this.data.act_data.lat),
        longitude: Number(this.data.act_data.lng),
        scale: 15,
        name: this.data.act_data.title,
        address: this.data.act_data.adress
      })
    }
  },
  /** 购买弹窗 */
  showBuyModal() {
    /** 是否已授权 */
    getApp().is_empower();
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "ease",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(), // export 方法每次调用后会清掉之前的动画操作。
      showModalStatus: true
    })
    setTimeout(() => {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export() // export 方法每次调用后会清掉之前的动画操作。
      })
      console.log(this)
    }, 200)
  },
  /** 隐藏 */
  hideBuyModal() {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "ease",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
      console.log(this)
    }.bind(this), 200)
  },
  bindKeyInput: function(e) {
    console.log(e);
    let item = e.currentTarget.dataset.model;
    this.setData({
      [item]: e.detail.value
    });
  },
  bindCustomFields: function(e) {
    let item = e.currentTarget.dataset.model;
    let data = this.data.customFields;
    data[item].fieldValue = e.detail.value
    this.setData({
      customFields: data
    });
  },
  /** 报名名单数据 */
  getEnrolls: function() {
    let that = this;
    let getEnrollsData = {
      other_id: this.data.id,
      page_index: 1,
      page_size: 5
    }
    wx.request({
      url: api.order.enrolls,
      data: getEnrollsData,
      header: {
        "content-type": "application/json"
      },
      method: 'GET',
      success(res) {
        console.log('报名名单数据')
        console.log(res)
        setTimeout(() => {
          wx.hideLoading()
          that.setData({
            enrollsData: res.data.data,
            enroll_num: res.data.data.length
          })
        }, 500)
      }
    })
  },
  toBuy: function() {
    var that = this;
    if (this.data.name == '' && this.data.business == '') {
      wx.showToast({
        title: '请填写完整',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    let sendData = {
      openId: app.globalData.wxUserInfo.openId,
      money: this.data.act_data.price,
      paymentMoney: this.data.act_data.price,
      name: this.data.name,
      communityId: this.data.comm_id,
      business: this.data.business,
      job: this.data.job,
      message: this.data.message,
      otherId: this.data.id,
      customFields: JSON.stringify(this.data.customFields),
      type: 1,
    }
    wx.request({
      url: api.active.tobuy,
      data: sendData,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success(res) {
        if (res.data.code == 200) {
          /** 支付返回 */
          wx.requestPayment({
            timeStamp: res.data.data.timeStamp,
            nonceStr: res.data.data.nonceStr,
            package: res.data.data.package,
            signType: res.data.data.signType,
            paySign: res.data.data.paySign,
            success(res) {
              console.log("支付成功");
            },
            fail(res) {
              wx.showToast({
                title: '报名失败',
                icon: 'none',
                duration: 2000
              })
            },
            /** 方法完成事件 */
            complete(res) {
              that.hideBuyModal();
              /** 支付成功 */
              if (res.errMsg == "requestPayment:ok") {
                that.setData({
                  pay_fail: '0',
                })
                /** 延迟1s 提示 */
                setTimeout(() => {
                  wx.showToast({
                    title: '报名成功',
                    image: '../../images/pay_ok_01.png',
                    duration: 2000
                  })
                }, 1000);
                /** 报名列表刷新 */
                that.getEnrolls();
              } else {
                /** 未支付成功 res.errMsg == "request:ok" */
                that.setData({
                  pay_fail: '1',
                })
              }
            }
          })
        } else if (res.data.code == 1005) {
          wx.showToast({
            title: '您已报名',
            image: '../../images/has_enroll.png',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '报名失败，请稍后再试',
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },

  /** 收藏 */
  follow: function() {
    let that = this;
    if (!app.globalData.wxUserInfo.openId) {
      wx.showToast({
        title: '请登录',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (this.data.isHavedCollect == 0) {
      let sendData = {
        otherId: this.data.id,
        type: 1,
        openId: app.globalData.wxUserInfo.openId,
        img: this.data.act_data.image,
        title: this.data.act_data.title
      }
      /** 添加收藏 */
      wx.request({
        url: api.follow.addFollow,
        data: sendData,
        method: "POST",
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        success(res) {
          if (res.data.code == 200) {
            wx.showToast({
              title: '已收藏',
              image: '../../images/col.png',
              duration: 2000
            })
            that.setData({
              isHavedCollect: 1
            })
          }
        }
      });
    } else if (this.data.isHavedCollect == 1) {
      let sendData = {
        other_id: this.data.id,
        open_id: app.globalData.wxUserInfo.openId
      }
      wx.request({
        url: api.follow.delFollow,
        data: sendData,
        method: "POST",
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        success(res) {
          if (res.data.code == 200) {
            that.setData({
              isHavedCollect: 0
            })
            wx.showToast({
              title: '已取消',
              image: '../../images/unclo_03.png',
              duration: 2000
            })
          }
        }
      });
    }
  },
  /** 分享朋友圈海报 */
  share_wechat_moments: function() {
    let that = this;
    /** 跳转到海报页面 */
    var path = getCurrentPages()[getCurrentPages().length - 1].route
    wx.navigateTo({
      url: `../share_moments/share_moments?act_img=` + this.data.act_data.image + '&act_title=' + this.data.act_data.title + '&path=' + path + '&act_id=' + this.data.id,
    })

  },
  //跳转报名列表
  enrolls: function(e) {
    wx.navigateTo({
      url: "../enrolls/enrolls?id=" + this.data.id
    });
  },
  formatRichText: function(html) {
    let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
      match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
      match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
      match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
      return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
      match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
      return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
    return newContent;
  },
  /** 返回社群首页 */
  onUnload: function () {
    wx.reLaunch({
      url: `/pages/community/community?communitiesId=${this.data.comm_id}`
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {}

});